import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { authAPI, userAPI } from '@/api'
import { ElMessage } from 'element-plus'
import request, { handleApiResponse } from '@/utils/request'

// 安全解析工具：处理 null/空字符串/'undefined'/'null'
const safeParse = (str, fallback = null) => {
  if (!str || str === 'undefined' || str === 'null') return fallback
  try { return JSON.parse(str) } catch { return fallback }
}

// 简单 JWT 解码（不校验签名，仅解析 payload）
const decodeJwt = (token) => {
  try {
    const payload = token.split('.')[1]
    const json = decodeURIComponent(atob(payload.replace(/-/g, '+').replace(/_/g, '/')).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''))
    return JSON.parse(json)
  } catch { return null }
}

export const useUserStore = defineStore('user', () => {
  // 用户：安全解析，避免 JSON.parse('undefined')
  const initialUser = safeParse(localStorage.getItem('user'), null)
  const user = ref(initialUser)

  // Token：安全解析
  const savedTokenObj = safeParse(localStorage.getItem('token'), null)
  const token = ref({
    accessToken: savedTokenObj?.accessToken || null,
    refreshToken: savedTokenObj?.refreshToken || null,
  })
  const loading = ref(false)

  const setToken = (obj) => {
    token.value = obj
    localStorage.setItem('token', JSON.stringify(obj))
  }

  const setUser = (obj) => {
    user.value = obj
    localStorage.setItem('user', JSON.stringify(obj))
  }

  // 初始化用户状态
  const init = async () => {
    try {
      const savedTokenStr = localStorage.getItem('token')
      const savedUserStr = localStorage.getItem('user')
      
      const tokenData = safeParse(savedTokenStr, null)
      const userData = safeParse(savedUserStr, null)

      if (tokenData) token.value = tokenData
      if (userData) user.value = userData

      // 若发现本地存的是无效字符串，顺便清理
      if (!tokenData && (savedTokenStr === 'undefined' || savedTokenStr === '')) {
        localStorage.removeItem('token')
      }
      if (!userData && (savedUserStr === 'undefined' || savedUserStr === '')) {
        localStorage.removeItem('user')
      }

      // 如果有 accessToken 但没有用户对象，尝试从 JWT 解码 uid 并拉取资料
      if (token.value?.accessToken && !user.value) {
        const payload = decodeJwt(token.value.accessToken)
        const uid = payload?.uid || payload?.user_id || payload?.userId || payload?.sub
        const nameFromToken = payload?.name || payload?.username
        if (uid) {
          try {
            const result = await userAPI.getUserInfo(uid)
            const userData = handleApiResponse(result, 'data')
            setUser(userData)
          } catch (e) {
            // 如果接口不可用，至少设置一个可读的显示名占位
            if (nameFromToken) setUser({ userName: nameFromToken })
          }
        } else if (nameFromToken) {
          setUser({ userName: nameFromToken })
        }
      }
    } catch (error) {
      console.error('初始化用户状态失败:', error)
    }
  }

  // 用户登录
  const login = async (credentials) => {
    try {
      loading.value = true
      const result = await authAPI.login(credentials)
      
      // 使用通用响应处理工具
      const loginData = handleApiResponse(result, 'data')
      
      // 保存token和用户信息
      setToken({
        accessToken: loginData.accessToken,
        refreshToken: loginData.refreshToken
      })
      setUser(loginData.user)
      
      ElMessage.success('登录成功！欢迎回来')
      return result
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 用户注册
  const register = async (userData) => {
    try {
      loading.value = true
      const result = await authAPI.register(userData)
      
      // 使用通用响应处理工具
      const registerData = handleApiResponse(result, 'data')
      
      // 注册成功后自动登录
      setToken({
        accessToken: registerData.accessToken,
        refreshToken: registerData.refreshToken
      })
      setUser(registerData.user)
      
      ElMessage.success('注册成功！欢迎加入涂色抢地盘！')
      return result
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 刷新令牌
  const refreshToken = async () => {
    try {
      if (!token.value.refreshToken) {
        throw new Error('没有刷新令牌')
      }
      
      const result = await authAPI.refreshToken(token.value.refreshToken)
      const refreshData = handleApiResponse(result, 'data')
      
      setToken({
        accessToken: refreshData.accessToken,
        refreshToken: refreshData.refreshToken
      })
      
      return result
    } catch (error) {
      console.error('刷新令牌失败:', error)
      // 刷新失败，清除用户状态
      logout()
      throw error
    }
  }

  // 获取用户信息
  const fetchUserInfo = async (userId) => {
    try {
      loading.value = true
      const result = await userAPI.getUserInfo(userId)
      const userData = handleApiResponse(result, 'data')
      setUser(userData)
      return result
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 若后端返回“用户不存在”等404场景，自动登出以清理脏状态
      if (error && typeof error.message === 'string' && (error.message.includes('不存在') || error.message.includes('未登录'))) {
        try { await logout() } catch (_) {}
      }
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新用户信息
  const updateUserInfo = async (userId, userData) => {
    try {
      loading.value = true
      const result = await userAPI.updateUser(userId, userData)
      const updateData = handleApiResponse(result, 'data')
      setUser(updateData)
      ElMessage.success('用户信息更新成功')
      return result
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (userId, passwordData) => {
    try {
      loading.value = true
      const result = await userAPI.changePassword(userId, passwordData)
      ElMessage.success('密码修改成功')
      return result
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 上传头像
  const uploadAvatar = async (userId, file) => {
    try {
      loading.value = true
      const result = await userAPI.uploadAvatar(userId, file)
      const avatarData = handleApiResponse(result, 'data')
      
      console.log('头像上传返回数据:', avatarData)
      
      // 更新用户信息中的头像 - 根据API响应结构处理
      if (user.value) {
        // 根据控制台日志，API返回的是 avatarUrl 字段
        user.value.avatar = avatarData.avatarUrl || avatarData.avatar || avatarData
        setUser(user.value)
        console.log('更新后的用户头像:', user.value.avatar)
      }
      ElMessage.success('头像上传成功')
      return result
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户等级
  const fetchUserLevel = async (userId) => {
    try {
      const result = await userAPI.getUserLevel(userId)
      const levelData = handleApiResponse(result, 'data')
      return levelData
    } catch (error) {
      console.error('获取用户等级失败:', error)
      throw error
    }
  }

  // 获取用户称号
  const fetchUserTitles = async (userId) => {
    try {
      const result = await userAPI.getUserTitles(userId)
      const titlesData = handleApiResponse(result, 'data')
      return titlesData
    } catch (error) {
      console.error('获取用户称号失败:', error)
      throw error
    }
  }

  // 忘记密码
  const forgetPassword = async (forgetData) => {
    try {
      loading.value = true
      const result = await authAPI.forgetPassword(forgetData)
      ElMessage.success('密码重置成功，请使用新密码登录')
      return result
    } catch (error) {
      console.error('忘记密码失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 验证用户信息
  const validateUserInfo = async (validateData) => {
    try {
      loading.value = true
      const result = await authAPI.validateUserInfo(validateData)
      return result
    } catch (error) {
      console.error('验证用户信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      // 清除本地状态
      user.value = null
      token.value = { accessToken: null, refreshToken: null }
      
      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      
      ElMessage.success('已退出登录')
      return { success: true }
    } catch (error) {
      console.error('退出登录失败:', error)
      throw error
    }
  }

  // 计算属性
  const isAuthenticated = computed(() => {
    return !!token.value.accessToken
  })

  const userDisplayName = computed(() => {
    if (isAuthenticated.value) {
      return user.value?.userName || user.value?.username || user.value?.name || '已登录用户'
    }
    return '未登录'
  })

  const userAvatar = computed(() => {
    return user.value?.avatar || '/default-avatar.png'
  })

  // 根据头像标识返回预览URL（与大厅一致的显示逻辑）
  const getAvatarPreviewUrl = (avatarIdOrUrl) => {
    if (!avatarIdOrUrl) return ''
    // 已是完整URL则直接返回
    if (typeof avatarIdOrUrl === 'string' && /^(https?:)?\/\//i.test(avatarIdOrUrl)) {
      return avatarIdOrUrl
    }
    // 否则按后端文件接口拼装：优先从 axios baseURL 推导，确保开发代理下含有 /api 前缀
    let base = ''
    try {
      base = (request?.defaults?.baseURL || '').replace(/\/+$/,'')
    } catch { base = (import.meta?.env?.VITE_API_BASE_URL || '') }
    return `${base}/users/avatar-file/${encodeURIComponent(avatarIdOrUrl)}`
  }

  return { 
    // 状态
    user, 
    token,
    loading,
    
    // 方法
    setToken, 
    setUser, 
    init, 
    login,
    register,
    refreshToken,
    fetchUserInfo,
    updateUserInfo,
    changePassword,
    uploadAvatar,
    fetchUserLevel,
    fetchUserTitles,
    forgetPassword,
    validateUserInfo,
    logout, 
    
    // 计算属性
    userDisplayName, 
    isAuthenticated,
    userAvatar,
    getAvatarPreviewUrl
  }
})